import { kmhq, kmlr, kmsc } from '@/services';
import ProList from '@ant-design/pro-list';
import { Button, Form, Input, message, Modal } from 'antd';
import { useEffect, useState } from 'react';

export default () => {
  const [dataSource, setDataSource] = useState<any[]>();
  const [form] = Form.useForm();

  useEffect(() => {
    getData();
  }, []);

  const getData = async () => {
    const data = await kmhq();
    if (data.msg === '失败') {
      return message.error(data.content);
    }
    setDataSource(data.content);
  };

  const handleOk = async () => {
    const values = await form.validateFields();
    const data = await kmlr(values);
    if (data.msg === '失败') {
      message.error(data.content);
    } else {
      message.success('添加成功');
      getData();
    }
  };

  const handleDel = async (id: string) => {
    Modal.confirm({
      content: '确认删除科目？',
      onOk: async () => {
        const data = await kmsc({ id });
        if (data.msg === '失败') {
          return message.error(data.content);
        }
        getData();
      },
    });
  };

  return (
    <div style={{ display: 'flex', height: '100%' }}>
      <div
        style={{
          width: '100%',
          height: '100%',
          marginRight: '8px',
          background: '#fff',
        }}
      >
        <ProList
          defaultSize="small"
          toolBarRender={() => {
            return [
              <Form layout="inline" form={form}>
                <Form.Item name="id" label="id">
                  <Input />
                </Form.Item>
                <Form.Item name="name" label="名称">
                  <Input />
                </Form.Item>
              </Form>,
              <Button key="add" type="primary" onClick={handleOk}>
                新建科目
              </Button>,
            ];
          }}
          rowKey="id"
          headerTitle="录入科目"
          dataSource={dataSource}
          showActions="always"
          metas={{
            title: {
              dataIndex: 'name',
              render: (_, record) => {
                return (
                  <div>
                    {record.id}： {record.name}
                  </div>
                );
              },
            },
            actions: {
              render: (_, record) => (
                <a onClick={() => handleDel(record.id)}>删除科目</a>
              ),
            },
          }}
        />
      </div>
    </div>
  );
};
